"""
日志窗口
"""
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QPlainTextEdit,
                           QPushButton, QHBoxLayout, QLabel)
from PyQt6.QtCore import Qt, pyqtSignal, pyqtSlot
import sys
from datetime import datetime

class LogWindow(QDialog):
    """日志窗口，用于显示脚本运行日志"""
    
    def __init__(self, parent=None, script_id=None, script_name=None):
        super().__init__(parent)
        self.script_id = script_id
        self.script_name = script_name
        self.setWindowTitle(f"扫货日志 - {script_name or f'脚本{script_id}'}")
        self.setFixedSize(800, 600)
        # 设置为模态窗口
        self.setWindowModality(Qt.WindowModality.ApplicationModal)
        
        # 存储已连接的信号源
        self.connected_signals = []
        
        self.setup_ui()
        
    def setup_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setSpacing(10)
        layout.setContentsMargins(20, 20, 20, 20)
        
        # 脚本ID和标题显示
        title_layout = QHBoxLayout()
        title_layout.setSpacing(10)
        title_layout.setContentsMargins(0, 0, 0, 0)
        
        script_id_label = QLabel(f"脚本ID：{self.script_id}")
        script_id_label.setStyleSheet("color: #606266; font-size: 12px;")
        
        script_name_label = QLabel(f"脚本名称：{self.script_name or ''}")
        script_name_label.setStyleSheet("color: #606266; font-size: 12px;")
        
        title_layout.addWidget(script_id_label)
        title_layout.addWidget(script_name_label)
        title_layout.addStretch()
        
        layout.addLayout(title_layout)
        
        # 日志文本框
        self.log_text = QPlainTextEdit()
        self.log_text.setReadOnly(True)
        self.log_text.setLineWrapMode(QPlainTextEdit.LineWrapMode.NoWrap)
        self.log_text.setStyleSheet("""
            QPlainTextEdit {
                background-color: #1e1e1e;
                color: #d4d4d4;
                font-family: Consolas, Monaco, monospace;
                font-size: 12px;
                padding: 10px;
                border: none;
                border-radius: 2px;
            }
        """)
        layout.addWidget(self.log_text)
        
        # 按钮区域
        btn_layout = QHBoxLayout()
        self.clear_btn = QPushButton("清除日志")
        self.close_btn = QPushButton("关闭")
        
        self.clear_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 15px;
                background-color: #409eff;
                color: white;
                border: none;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton:hover {
                background-color: #66b1ff;
            }
        """)
        
        self.close_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 15px;
                background-color: white;
                color: #606266;
                border: 1px solid #dcdfe6;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton:hover {
                color: #409eff;
                border-color: #c6e2ff;
                background-color: #ecf5ff;
            }
        """)
        
        self.clear_btn.clicked.connect(self.clear_log)
        self.close_btn.clicked.connect(self.close)
        
        btn_layout.addWidget(self.clear_btn)
        btn_layout.addWidget(self.close_btn)
        btn_layout.addStretch()
        
        layout.addLayout(btn_layout)
        
    @pyqtSlot(str)
    def append_log(self, text: str):
        """添加日志"""
        try:
            # 添加时间戳
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            log_text = f"[{timestamp}] {text}"
            
            # 添加到日志窗口
            self.log_text.appendPlainText(log_text.rstrip())
            
            # 滚动到底部
            self.log_text.verticalScrollBar().setValue(
                self.log_text.verticalScrollBar().maximum()
            )
        except Exception as e:
            print(f"添加日志失败: {str(e)}")
        
    def clear_log(self):
        """清除日志"""
        self.log_text.clear()
        
    def connect_signal_source(self, source):
        """连接信号源"""
        if hasattr(source, 'log_signal'):
            source.log_signal.connect(self.append_log)
            self.connected_signals.append(source)
            
    def disconnect_all_signals(self):
        """断开所有信号连接"""
        for source in self.connected_signals:
            if hasattr(source, 'log_signal'):
                try:
                    source.log_signal.disconnect(self.append_log)
                except:
                    pass
        self.connected_signals.clear()
        
    def closeEvent(self, event):
        """窗口关闭事件"""
        self.disconnect_all_signals()
        super().closeEvent(event)
